<?php
set_include_path("../include;include");
require_once '/util/globals.php';
require_once '/dao/Database.php';
require_once '/model/Member.php';
require_once '/model/Group.php';

/**
 * database access class for Group
 *
 * @author Thomas Crepain <contact@thomascrepain.be>
 */
class GroupDAO
{
        const TABLENAME = 'age_group';

	/**
	 *
	 *
	 * @var Database
	 */
	private $db;

	/**
	 * Contains the group cache
	 *
	 * @var array
	 */
	private $groupCache = array();

	/**
	 * unique instance of this class
	 * Singleton pattern
	 *
	 * @var Database
	 */
	private static $uniqueInstance;


	/**
	 * constructs the DAO
	 */
	private function __construct()
	{
		// get database
                $this->db = Database::getInstance();
	}

	/**
	 * gets instance of database
	 *
	 * @return GroupDAO
	 */
	public static function getInstance()
	{
		if(!isset(self::$uniqueInstance))
		{
			self::$uniqueInstance = new self();
		}

		return self::$uniqueInstance;
	}

	/**
	 * Returns the name
	 *
	 * @return String
	 */
	public function getNameByGroupId(integer $groupId)
	{
		// build cache
		$this->buildCache($groupId);

		return $this->groupCache[$groupId]['name'];
	}


	/**
	 * Build the cache for the groupId if needed
	 *
	 * @param integer	$groupId
	 */
	private function buildCache(integer $groupId)
	{
		// if cache is not build
		if(!isset($this->groupCache[$groupId]))
		{
                    // fill cache with this group
                    $this->groupCache[$groupId] = $this->db->getRecord("SELECT g.group_id, g.name
                                                                            FROM ".self::TABLENAME." AS g
                                                                            WHERE g.group_id = ?",
                                                                            array($groupId));
		}
	}


        /**
         * Saves the given member in the database
         *
         * @param Group $group
         * @return integer $id  id in database
         */
        public function save(Group $group){
            $id = 0;

            // is this a new member?
            if(is_null($group->getId())){
                $id = $this->db->insert(self::TABLENAME, array(
                        'name' => $group->getName()));
            } else {
                $id = $group->getId();

                $this->db->update(self::TABLENAME, array(
                        'name' => $group->getName()));
            }

            return $id;
        }
}

?>